from modules import *
# 图像分割（灰度阈值分割）
def seg(img):
    rows,cols = img.shape
    left_top = []
    right_bot = []
    #获得最上面的索引
    for i in range(rows):
        for j in range(cols):
            if img[i,j] != 0 :
                left_top.append(i)
                break
    # 获得left索引
    for i in range(cols):
        for j in range(rows):
            if img[j,i] != 0 :
                left_top.append(i)
                break
    # 获得bot索引
    for i in range(rows-1,-1,-1):
        for j in range(cols-1,-1,-1):
            if img[i,j] != 0 :
                right_bot.append(i)
                break
    # 获得right索引
    for i in range(cols-1,-1,-1):
        for j in range(rows-1,-1,-1):
            if img[j,i] != 0 :
                right_bot.append(i)
                break
    rows_slice = slice(left_top[0],right_bot[0])
    cols_slice = slice(left_top[1],right_bot[1])
    img = img[rows_slice,cols_slice]
    return(img)
    
    # # 使用NumPy的argwhere函数找到非零元素的位置
    # non_zero_positions = np.argwhere(img != 0)

    # # 如果图像中没有非零元素，直接返回原始图像
    # if non_zero_positions.size == 0:
    #     return img
    
    # # 使用NumPy的argwhere函数找到非零元素的位置
    # non_zero_positions = np.argwhere(img != 0)
    
    # # 计算边界位置
    # left_border = non_zero_positions[:, 0].min()
    # right_border = non_zero_positions[:, 0].max()
    # top_border = non_zero_positions[:, 1].min()
    # bottom_border = non_zero_positions[:, 1].max()
    
    # # 创建切片
    # rows_slice = slice(top_border, bottom_border + 1)
    # cols_slice = slice(left_border, right_border + 1)
    
    # # 切片并返回图像
    # return img[rows_slice, cols_slice]


def seg_resize(img):
    img = seg(img)
    img = cv2.resize(img,(224,224),interpolation=cv2.INTER_AREA)
    return(img)